package com.changhong.wlyspectrum.MainTestActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.Attributes;
import com.changhong.wlyspectrum.utils.MyEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by Mr_tao
 * on 2017/3/9.
 */
public class TestDataActivity extends Activity{
    private final static String TAG = "TestDataActivity";
    private ImageView mBackIv;
    private LinearLayout mlinearLayout;
    private EditText mWetEdt;
    private EditText mStarchEdt;
    private EditText mAcidityEdt;
    private EditText mSugarEdt;
    private Button mNextBtn;
    private String mWet;
    private String mStarch;
    private String mAcidity;
    private String mSugar;
    private String[] names;
    private MyEditText[] myEditTexts;
    private MyEditText myEditText;
    private String collectionId;
    private String user_id;
    private String token;
    private JSONArray mJsonArray = null;
    private int mScreenWidth;
    private int mScreenHeight;
    private float mScale;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_data_new_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_test_data);

        InitData();

        //InitUi();
    }

    private void InitData(){
        Intent intent = getIntent();
        collectionId = intent.getStringExtra("collectionId");
        Log.e(TAG,"collectionId----->" + collectionId);

        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");

        Log.e(TAG,"GetCollectionByIdStart");
        GetCollectiodById();
        Log.e(TAG,"GetCollectionByIdEnd");
    }
    private void InitUi() {
        mBackIv = (ImageView)findViewById(R.id.test2wuliangye);
        mBackIv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mlinearLayout = (LinearLayout)findViewById(R.id.my_linear);
        myEditTexts = new MyEditText[mJsonArray.length()];
        names = new String[mJsonArray.length()];
        for(int i = 0;i < mJsonArray.length();i++){
            myEditText = new MyEditText(TestDataActivity.this,null);
            TextView mytext = (TextView)myEditText.findViewById(R.id.my_name);
            EditText myedit = (EditText)myEditText.findViewById(R.id.my_descri);
            try {
                JSONObject info = (JSONObject)mJsonArray.get(i);
                mytext.setText(info.getString("name") + ":");
                //myedit.setHint("请输入" + info.getString("description"));
                myedit.setHint(getResources().getString(R.string.annotated));
                names[i] = info.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            myEditTexts[i] = myEditText;
            mlinearLayout.addView(myEditTexts[i]);
        }

        WindowManager wm = (WindowManager)this.getSystemService(Context.WINDOW_SERVICE);
        mScreenWidth = wm.getDefaultDisplay().getWidth();
        mScreenHeight = wm.getDefaultDisplay().getHeight();
        mScale = this.getApplicationContext().getResources().getDisplayMetrics().density;
        Log.i(TAG, "window width:"+mScreenWidth+" height:"+mScreenHeight+" density:"+mScale);
        mNextBtn = new Button(TestDataActivity.this);
        mNextBtn.setBackgroundColor(getResources().getColor(R.color.white));
        mNextBtn.setText(getString(R.string.next));
        mNextBtn.setTextColor(getResources().getColor(R.color.button_text_color));
        mNextBtn.setTextSize(8*mScale);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(mScreenWidth*4/5,(int)(50*mScale));
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
        layoutParams.topMargin = (int)(20*mScale);
        mNextBtn.setLayoutParams(layoutParams);
        mlinearLayout.addView(mNextBtn);

        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean IsStart = false;
                HashMap<String,String> hashMap = new HashMap<String,String>();
                for(int i = 0;i < mJsonArray.length();i++){
                    if(myEditTexts[i].getText().length() != 0){
                        hashMap.put(names[i],myEditTexts[i].getText());
                        IsStart = true;
                    }else{
                        IsStart = false;
                        Toast.makeText(getApplicationContext(),"请输入完整的成分信息",Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
                if(IsStart){
                    Intent intent = new Intent(TestDataActivity.this,TestResultActivity.class);
                    intent.putExtra("hashmap",hashMap);
                    intent.putExtra("collectionId",collectionId);
                    startActivity(intent);
                }
            }
        });
        /*mWetEdt = (EditText)findViewById(R.id.mwet);
        mWetEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mWetEdt.setHint(null);
                } else {
                    if (mWetEdt.getText().length() != 0) {
                        mWetEdt.setHint(null);
                    } else {
                        mWetEdt.setHint(R.string.input_wet);
                    }
                }

            }
        });
        mWetEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mWetEdt.getText().length() != 0) {
                    mWetEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mStarchEdt = (EditText)findViewById(R.id.mstarch);
        mStarchEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mStarchEdt.setHint(null);
                } else {
                    if (mStarchEdt.getText().length() != 0) {
                        mStarchEdt.setHint(null);
                    } else {
                        mStarchEdt.setHint(R.string.input_starch);
                    }
                }

            }
        });
        mStarchEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mStarchEdt.getText().length() != 0) {
                    mStarchEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mAcidityEdt = (EditText)findViewById(R.id.macidity);
        mAcidityEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mAcidityEdt.setHint(null);
                } else {
                    if (mAcidityEdt.getText().length() != 0) {
                        mAcidityEdt.setHint(null);
                    } else {
                        mAcidityEdt.setHint(R.string.input_acidity);
                    }
                }

            }
        });
        mAcidityEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mAcidityEdt.getText().length() != 0) {
                    mAcidityEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mSugarEdt = (EditText)findViewById(R.id.msugar);
        mSugarEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mSugarEdt.setHint(null);
                } else {
                    if (mSugarEdt.getText().length() != 0) {
                        mSugarEdt.setHint(null);
                    } else {
                        mSugarEdt.setHint(R.string.input_sugar);
                    }
                }

            }
        });
        mSugarEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mSugarEdt.getText().length() != 0) {
                    mSugarEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mNextBtn = (Button)findViewById(R.id.test_next_btn);
        mNextBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mWet = mWetEdt.getText().toString();
                mStarch = mStarchEdt.getText().toString();
                mAcidity = mAcidityEdt.getText().toString();
                mSugar = mSugarEdt.getText().toString();
                if(!mWet.isEmpty()){
                    if(!mStarch.isEmpty()){
                        if(!mAcidity.isEmpty()){
                            if(!mSugar.isEmpty()){
                                Intent intent = new Intent(TestDataActivity.this,TestResultActivity.class);
                                intent.putExtra("wet", mWet);
                                intent.putExtra("starch", mStarch);
                                intent.putExtra("acidity", mAcidity);
                                intent.putExtra("sugar", mSugar);
                                intent.putExtra("collectionId",collectionId);
                                startActivity(intent);
                            }else{
                                Toast.makeText(getApplicationContext(), getString(R.string.input_sugar), Toast.LENGTH_SHORT).show();
                            }
                        }else{
                            Toast.makeText(getApplicationContext(), getString(R.string.input_acidity), Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(), getString(R.string.input_starch), Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(getApplicationContext(), getString(R.string.input_wet), Toast.LENGTH_SHORT).show();
                }
            }
        });*/
    }

    private Handler TestDataHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    InitUi();
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(), R.string.service_error, Toast.LENGTH_LONG).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    private void GetCollectiodById(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String path = "/collection/" + collectionId;
                try {
                    Response response = HttpMethods.TGetResponse(path,user_id,token);
                    Log.e(TAG,"response----->" + response);
                    if(response.isSuccessful()){
                        String result = response.body().string();

                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        Log.e(TAG,"jsonObject----->" + jsonObject);
                        String code = jsonObject.getString("code");
                        Log.e(TAG,"code----->" + code);
                        if(code.compareTo("0") == 0){
                            JSONArray jsonArray = new JSONArray(jsonObject.getString("jsonObj"));
                            JSONObject jsonobj = new JSONObject(jsonArray.getString(0));
                            collectionId = jsonobj.getString("collectionId");
                            String attri = jsonobj.getString("attributeTemplate");
                            mJsonArray = new JSONArray(attri);
                            Log.e(TAG,mJsonArray.length() + "");
                            TestDataHandler.sendMessage(Message.obtain(TestDataHandler, 0));
                        }else{
                            JSONArray jsonArray = new JSONArray(jsonObject.getString("jsonObj"));
                            JSONObject jsonobj = new JSONObject(jsonArray.getString(0));
                            Log.e(TAG,"jsonobj----->" + jsonobj);
                            TestDataHandler.sendMessage(Message.obtain(TestDataHandler, 98));
                        }
                    }else{
                        TestDataHandler.sendMessage(Message.obtain(TestDataHandler, 99));
                    }
                } catch (IOException e) {
                    TestDataHandler.sendMessage(Message.obtain(TestDataHandler, 99));
                    e.printStackTrace();
                }catch (JSONException e){
                    TestDataHandler.sendMessage(Message.obtain(TestDataHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
